import dayjs from 'dayjs';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { EntityCondition } from 'src/utils/types/entity-condition.type';
import { Repository } from 'typeorm';
import { AdminUser } from './entities/admin-user.entity';
import { CreateAdminUserDto } from './dto/creater-user.dto';
import { responseData } from '../common/response.handle';
import { generateUserId, md5password } from '../utils/crypto-util';
import { IPaginationOptions } from '../utils/types/pagination-options';
import { UpdateAdminUserDto } from './dto/update-user.dto';

@Injectable()
export class AdminUsersService {
	constructor(
		@InjectRepository(AdminUser)
		private usersRepository: Repository<AdminUser>,
	) {}

	async create(createAdminUserDto: CreateAdminUserDto) {
		createAdminUserDto.password = md5password(createAdminUserDto.password);
		const userId = generateUserId();
		await this.usersRepository.save(
			this.usersRepository.create({
				...createAdminUserDto,
				userId,
			}),
		);
		return responseData(null, '创建角色成功');
	}

	async update(userId: string, updateAdminUserDto: UpdateAdminUserDto) {
		if (updateAdminUserDto.password) {
			updateAdminUserDto.password = md5password(updateAdminUserDto.password);
		}

		await this.usersRepository.update(userId, updateAdminUserDto);
		return responseData(null, '修改角色成功');
	}

	findOne(fields: EntityCondition<AdminUser>) {
		return this.usersRepository
			.createQueryBuilder('user')
			.where(fields)
			.addSelect('user.password') // 添加隐藏的字段
			.getOne();
	}

	// 分页查询
	async findListByPage(paginationOptions: IPaginationOptions) {
		const [users, total] = await this.usersRepository
			.createQueryBuilder('adminUser')
			.leftJoinAndSelect('adminUser.role', 'role')
			.where('username LIKE :username OR nickname LIKE :nickname', {
				username: `%${paginationOptions.keyword}%`,
				nickname: `%${paginationOptions.keyword}%`,
			})
			.skip((paginationOptions.pageNum - 1) * paginationOptions.pageSize)
			.take(paginationOptions.pageSize)
			.getManyAndCount();
		return responseData(
			{
				list: users,
				total,
				totalPages: Math.ceil(total / paginationOptions.pageSize),
			},
			'查询权限列表成功',
		);
	}

	async remove(userId: string) {
		await this.usersRepository.delete(userId);
		return responseData(null, '删除管理员成功');
	}

	async updateLoginTime(userId: string) {
		return this.usersRepository.update(userId, {
			recentLoginTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
		});
	}
}
